<?php
/*
Plugin Name: Contact Plugin
Description: A contact plugin to let user leave message
Author: Rex Zhou
Version: 0.1
*/
define('MY_PLUGIN_VERSION_NUM', '1.0');
define('MY_PLUGIN_MINIMUM_WP_VERSION', '4.0');
global $wpdb;
define('MY_NEW_TABLE', $wpdb->prefix . 'contact_table');
register_activation_hook(__FILE__, 'plugin_activation_cretable');
register_activation_hook(__FILE__, 'plugin_activation_insertdate');
register_deactivation_hook(__FILE__, 'plugin_deactivation_deltable');
add_action('plugins_loaded', 'myplugin_update_db_check');
add_action('admin_menu', 'contact_plugin_setup_menu');
add_action('wp_ajax_nopriv_contact_post_ajax', 'contact_post_ajax');
add_action('wp_ajax_contact_post_ajax', 'contact_post_ajax');
add_action('wp_ajax_nopriv_contact_get_ajax', 'contact_get_ajax');
add_action('wp_ajax_contact_get_ajax', 'contact_get_ajax');
//add_action('admin_head', 'my_custom_admin_head');
// function my_custom_admin_head() {
//     echo '<style>body {background-color: #4AAF48 !important;}</style>';
// }
//add_action('admin_menu', 'my_plugin_menu');
//add_action('admin_notices', 'my_plugin_admin_notices' );
//加入消息提醒

function contact_get_ajax() {
  global $wpdb;

  $data['pageIndex'] = esc_sql($_GET['pageIndex']);
  $data['pageSize'] = esc_sql($_GET['pageSize']);
  set_transient( 'totalRows', 1000, 60*60*12 );
  $total = $wpdb->get_var("SELECT COUNT(*) FROM ".MY_NEW_TABLE);
  $result['total']=$total;
  $rows = $wpdb->get_results("SELECT * FROM ".MY_NEW_TABLE." LIMIT ".$data['pageIndex']*$data['pageSize'].",".$data['pageSize']);
  $result['rows']=$rows;
  echo json_encode($result);
  die();


}
//ajax 接收数据
function contact_post_ajax() {

  global $wpdb;

  $data['username'] = esc_sql($_POST['username']);
  $data['phone'] = esc_sql($_POST['phone']);
  $data['industry']  =esc_sql($_POST['industry']);
  $data['date']  = time();
  //
  // $wpdb->insert(MY_NEW_TABLE, $data);

  global $wpdb;

  // $data['username'] = '我的博客';
  // $data['phone'] = '110';
  // $data['industry']  = '广告';
  // $data['date']  = time();

  $wpdb->insert(MY_NEW_TABLE, $data);

  echo 'success';
  die();
  //echo $wpdb;


}
add_action('wp_footer', 'footer_contact_js', 100);
function footer_contact_js() {

?>

<script>
(function($) {
  $(document).ready(function(){


    function PathLoader(el) {
	this.el = el;
    this.strokeLength = el.getTotalLength();

    // set dash offset to 0
    this.el.style.strokeDasharray =
    this.el.style.strokeDashoffset = this.strokeLength;
}

PathLoader.prototype._draw = function (val) {
    this.el.style.strokeDashoffset = this.strokeLength * (1 - val);
}

PathLoader.prototype.setProgress = function (val, cb) {
	this._draw(val);
    if(cb && typeof cb === 'function') cb();
}

PathLoader.prototype.setProgressFn = function (fn) {
	if(typeof fn === 'function') fn(this);
}

var body = document.body,
    svg = document.querySelector('svg path');



      // document.addEventListener('click', function () {
      //
      //     if(document.body.classList.contains('active')) {
      //         document.body.classList.remove('active');
      //         svg.setProgress(0);
      //         return;
      //     }
      //     document.body.classList.add('active');
      //     svg.setProgress(1);
      // });


    $('.footer-contact-submit').on('click',function(){

      if($('#username').val()==""|| $('#phone').val()==""){
        return false;
      }

      var data = {
      action: 'contact_post_ajax',
      username: $('#username').val(),
      phone: $('#phone').val(),
      industry:$('#industry').val()
      };

      // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
      $.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function(response) {
        //alert('Got this from the server: ' + response);
        $('.contact-fill-form').hide();
        $('.contact-text').hide();
        $('.success-message').show();

        if(svg !== null) {
            svg = new PathLoader(svg);

            setTimeout(function () {
                document.body.classList.add('active');
                svg.setProgress(1);
            }, 200);
        }
      });


    })


  });
 }(jQuery));

 </script>



<?php
}



// function my_plugin_menu() {
// 	// Add the new admin menu and page and save the returned hook suffix
// 	$hook_suffix = add_options_page('My Plugin Options', 'My Plugin', 'manage_options', 'my-unique-identifier', 'my_plugin_options');
// 	// Use the hook suffix to compose the hook and register an action executed when plugin's options page is loaded
// 	add_action( 'load-' . $hook_suffix , 'my_load_function' );
// }

// function my_load_function() {
// 	// Current admin page is the options page for our plugin, so do not display the notice
// 	// (remove the action responsible for this)
// 	remove_action( 'admin_notices', 'my_plugin_admin_notices' );
// }

// function my_plugin_admin_notices() {
// 	echo "<div id='notice' class='updated fade'><p>My Plugin is not configured yet. Please do it now.</p></div>\n";
// }

function plugin_activation_cretable() {
    global $wpdb;
    $charset_collate = '';

    if (!empty($wpdb->charset)) {
      $charset_collate = "DEFAULT CHARACTER SET {$wpdb->charset}";
    }

    if (!empty( $wpdb->collate)) {
      $charset_collate .= " COLLATE {$wpdb->collate}";
    }

    $sql = "CREATE TABLE " . MY_NEW_TABLE . " (
     `id` int(11) NOT NULL auto_increment,
     `username` varchar(255) NOT NULL,
     `phone` varchar(255) NOT NULL,
     `industry` varchar(255) NOT NULL,
     `date` int(11) NOT NULL,
     `iscontact` tinyint(4) NOT NULL DEFAULT '0',
      UNIQUE KEY id (id)
   ) $charset_collate;";

   require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );

  //  $sql2="ALTER TABLE " . MY_NEW_TABLE . " ADD PRIMARY KEY (`id`);";
  //  $sql3="ALTER TABLE " . MY_NEW_TABLE . " MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;";
   dbDelta( $sql );
  //  dbDelta( $sql2 );
  //  dbDelta( $sql3 );

   // update_option()方法，在options表里如果不存在更新字段，则会创建该字段,存在则更新该字段
   update_option('my_plugin_version_num', MY_PLUGIN_VERSION_NUM);
}
function plugin_activation_insertdate() {

   global $wpdb;

   $data['username'] = '我的博客';
   $data['phone'] = '110';
   $data['industry']  = '广告';
   $data['date']  = time();

   $wpdb->insert(MY_NEW_TABLE, $data);


}

function plugin_deactivation_deltable() {
    global $wpdb;

    $wpdb->query("DROP TABLE IF EXISTS " . MY_NEW_TABLE);
    delete_option('my_plugin_version_num');
}


function myplugin_update_db_check() {
    // 获取到options表里的插件版本号 不等于 当前插件版本号时，运行创建表方法，更新数据库表
    if (get_option('my_plugin_version_num') != MY_PLUGIN_VERSION_NUM) {
        plugin_activation_cretable();
    }
}



function contact_plugin_setup_menu(){
      add_menu_page( 'Contact Plugin Page', '联系人', 'manage_options', __FILE__,  'baw_settings_page','dashicons-editor-alignleft');
      add_submenu_page(__FILE__,'查看联系人','查看联系人', 'manage_options', 'contact-sub-menu1', 'view_all_contacts');
      add_action( 'admin_init', 'register_mysettings' );
      // set_menu_icon_class(__FILE__, 'menu_dashicons-editor-alignleft');
}
add_action('admin_menu', 'appearance_submenu');

function baw_settings_page() {
?>
<div class="wrap">
<h2>你的插件名称</h2>

<form method="post" action="options.php">
    <?php settings_fields( 'baw-settings-group' ); // 设置字段 这个函数取代了 nonce magic, action field, and page_options ?>
    <?php do_settings_sections( 'baw-settings-group' ); // 这个函数取代了表单字段标记形式本身 ?>
    <table class="form-table">
        <tr valign="top">
        <th scope="row">New Option Name</th>
        <td><input type="text" name="new_option_name" value="<?php echo esc_attr( get_option('new_option_name') ); ?>" /></td>
        </tr>

        <tr valign="top">
        <th scope="row">Some Other Option</th>
        <td><input type="text" name="some_other_option" value="<?php echo esc_attr( get_option('some_other_option') ); ?>" /></td>
        </tr>

        <tr valign="top">
        <th scope="row">Options, Etc.</th>
        <td><input type="text" name="option_etc" value="<?php echo esc_attr( get_option('option_etc') ); ?>" /></td>
        </tr>
    </table>
    <?php submit_button(); ?>
</form>
</div>
<?php }

function appearance_submenu() {
  add_theme_page(__('插件设置'), __('插件设置'), 'administrator', 'your-unique-identifier', 'add_appearance_submenu');
}

function add_appearance_submenu() {
  echo '<div><p>这儿就是主题插件设置的地方.</p></div>';
}

add_action('admin_menu', 'dashboard_submenu');
function dashboard_submenu() {
    add_dashboard_page(__('仪表盘设置'), __('仪表盘设置'), 'read', 'your-unique-identifier', 'add_dashboard_submenu');
}
function add_dashboard_submenu() {
  echo '<div><p>这儿就是仪表盘菜单设置的地方.</p></div>';
}



function register_mysettings() {
    // 注册我们的设置
    register_setting( 'baw-settings-group', 'new_option_name' );
    register_setting( 'baw-settings-group', 'some_other_option' );
    register_setting( 'baw-settings-group', 'option_etc' );
}



function test_init(){
  if($_POST['test_hidden'] == 'y') {
   update_option('test_input_c',$_POST['test_insert_options']); //更新你添加的数据库
?>
 <div id="message" style="background-color: green; color: #ffffff;">保存成功 !</div>
<?php
}
?>
<div>
  <?php screen_icon(); //显示图标  ?>
  <h2>添加数据</h2>
  <form action="" method="post" id="my_plugin_test_form">
      <h3>
          <label for="test_insert_options">输入测试数据:</label>
          <input type="text" id="test_insert_options" name="test_insert_options" value="<?php  echo esc_attr(get_option('test_input_c')); ?>"  />
      </h3>
      <p>
          <input type="submit" name="submit" value="保存" class="button button-primary" />
          <input type="hidden" name="test_hidden" value="y"  />
      </p>
  </form>
</div>
<?php
}

function view_all_contacts(){
    //查看所有联系人

    wp_register_style( 'prefix-style', plugins_url('style.css', __FILE__) );
    wp_register_style( 'pagination', plugins_url('js/mricode.pagination.css', __FILE__) );
    wp_register_script( 'pagination', plugins_url('js/mricode.pagination.js', __FILE__), array( 'jquery' ) );
    wp_enqueue_style( 'prefix-style' );
    wp_enqueue_style( 'pagination' );
    wp_enqueue_script( 'pagination' );
    //wp_register_script( 'jquery', get_template_directory_uri() . '/js/jquery-1.11.1.min.js', false, '1.0', false );
    //wp_enqueue_script( 'jquery' );

    //global $wpdb;
    //$charset_collate = '';

    //$fivesdrafts = $wpdb->get_results("SELECT * FROM ".MY_NEW_TABLE." LIMIT 0,5");


    ?>

    <div class="wrapper">

  <div class="table" id="contact_wp_table">

    <div class="row header">
      <div class="cell">
        姓名
      </div>
      <div class="cell">
        手机号码
      </div>
      <div class="cell">
        行业
      </div>
      <div class="cell">
        时间
      </div>
      <div class="cell">
        是否已联系
      </div>
    </div>











  </div>
  <div id="page" class="m-pagination"></div>
  <div id="eventLog"></div>
</div>
<script type="text/javascript">

(function($) {
  function timeStamp2String (time){
        var datetime = new Date();
         datetime.setTime(time*1000);
         var year = datetime.getFullYear();
         var month = datetime.getMonth() + 1;
         var date = datetime.getDate();
         var hour = datetime.getHours();
         var minute = datetime.getMinutes();
         var second = datetime.getSeconds();
         var mseconds = datetime.getMilliseconds();
         return year + "-" + month + "-" + date+" "+hour+":"+minute+":"+second;
};
  $(document).ready(function(){
    $("#page").pagination({
                  pageIndex: 0,
                  pageSize: 5,
                  total: 100,
                  debug: true,
                  showInfo: true,
                  showJump: true,
                  showPageSizes: true,
                  loadFirstPage: true,
                  remote: {
                      url: '<?php echo admin_url('admin-ajax.php?action=contact_get_ajax'); ?>',
                      params: $('form').serializeArray(),
                      success: function (data) {
                          //var data=JSON.stringify(data);

                          $('#contact_wp_table .timerow').remove();
                          $.each(data['rows'], function(p1, p2){
                            console.log(p2)
                            $('<div class="row timerow">\
                            <div class="cell">\
                              '+p2.username+'\
                            </div>\
                            <div class="cell">\
                                '+p2.phone+'\
                            </div>\
                            <div class="cell">\
                                '+p2.industry+'\
                            </div>\
                            <div class="cell">\
                              '+timeStamp2String(p2.date)+'\
                            </div>\
                            <div class="cell">\
                              '+p2.iscontact+'\
                            </div>\
                            </div>').appendTo($('#contact_wp_table'));

                          })



                          //console.log(JSON.stringify(data))
                          //$("#eventLog").append(' remote callback : ' + JSON.stringify(data) + '<br />');
                      }
                  }
              });
});
}(jQuery));
</script>


<?php
}
?>
